package java.com.it.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.reggie.common.BaseContext;
import com.it.reggie.common.CustomException;
import com.it.reggie.dto.OrderDto;
import com.it.reggie.entity.*;
import com.it.reggie.mapper.OrderMapper;
import com.it.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderService orderService;

    /**
     * 用户下单
     *
     * @param orders
     */
    @Transactional//事务控制
    public void submit(Orders orders) {
        //获得当前用户id
        Long userId = BaseContext.getCurrentId();
        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);

        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomException("购物车为空");
        }
        //查询用户数据
        User user = userService.getById(userId);
        //查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);

        if (addressBook == null) {
            throw new CustomException("用户地址信息有误");
        }

        long orderId = IdWorker.getId();//订单号
        //计算工具，原子操作，可以保证多线程的情况下计算也不会有问题
        AtomicInteger amount = new AtomicInteger(0);

        //遍历购物车数据
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();//创建订单明细实体
            orderDetail.setOrderId(orderId);//订单编号
            orderDetail.setNumber(item.getNumber());//菜品或套餐的数量（份数）
            orderDetail.setDishFlavor(item.getDishFlavor());//口味
            orderDetail.setDishId(item.getDishId());//菜品id
            orderDetail.setSetmealId(item.getSetmealId());//套餐id
            orderDetail.setName(item.getName());//菜品名称/套餐名称
            orderDetail.setImage(item.getImage());//图片名称
            orderDetail.setAmount(item.getAmount());//当前金额(单份金额)
            //累加方法，相当于+=，从0开始累加：单个金额 * 份数 = int ？（总金额：amount）
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //向订单表插入数据，一个单对应一条数据，因此也是插入一条数据
        orders.setId(orderId);//订单id
        orders.setOrderTime(LocalDateTime.now());//系统当前时间
        orders.setCheckoutTime(LocalDateTime.now());//支付时间
        orders.setStatus(2);//待派送状态
        orders.setAmount(new BigDecimal(amount.get()));//订单总金额
        orders.setUserId(userId);//用户id
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setUserName(user.getName());//用户数据
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setPhone(addressBook.getPhone());//手机号
        orders.setAddress(//订单地址拼接
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())//省
                        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())//市
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())//区
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));//地址表详细信息
        //将上列数据插入订单表
        this.save(orders);
        //向订单明细表插入数据，可能是插入多条数据
        orderDetailService.saveBatch(orderDetails);
        //清空购物车数据
        shoppingCartService.remove(wrapper);
    }

    /**
     * 根据订单 id 来得到一个订单明细的集合
     *
     * @param orderId
     * @return
     */
    public List<OrderDetail> getOrderDetailListByOrderId(Long orderId) {
    /*
	    此处为从 [用户查看自己的订单信息] 功能代码中抽离的一个方法
	    旨在通过订单的 id 来查询订单明细，得到一个订单明细的集合

	    单独抽离出来是为了避免在 stream 中遍历时
	    直接使用的构造条件来查询导致 eq 叠加
	    从而导致后面查询的数据都是 null
    */
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, orderId);
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);
        return orderDetailList;
    }

    /**
     * 用户查看自己的订单信息
     *
     * @param ordersPageInfo
     * @param ordersDtoPageInfo
     * @return
     */
    @Transactional
    public void page(Page<Orders> ordersPageInfo, Page<OrderDto> ordersDtoPageInfo) {
        //构造条件查询对象
        LambdaQueryWrapper<Orders> queryWrapper_1 = new LambdaQueryWrapper<Orders>();
        //这里是直接把当前用户分页的全部结果查询出来，要添加用户 id 作为查询条件，否则会出现用户可以查询到其他用户的订单的情况
        queryWrapper_1.eq(Orders::getUserId, BaseContext.getCurrentId());
        //添加排序条件，根据更新时间降序排列
        queryWrapper_1.orderByDesc(Orders::getOrderTime);

        //分页查询（queryWrapper_1 -> ordersPageInfo）
        orderService.page(ordersPageInfo, queryWrapper_1);

        //对 OrderDto 进行必要的属性赋值
        List<Orders> records = ordersPageInfo.getRecords();
        List<OrderDto> orderDtoList = records.stream().map((item) -> {
            OrderDto orderDto = new OrderDto();
            Long orderId = item.getId();//获取订单 id

            //通过订单的 id 来查询订单明细，得到一个订单明细的集合
            List<OrderDetail> orderDetailList = this.getOrderDetailListByOrderId(orderId);

            //为 orderDetails 里面的属性赋值
            BeanUtils.copyProperties(item, orderDto);

            //对 orderDto 进行 OrderDetails 属性的赋值
            orderDto.setOrderDetails(orderDetailList);

            return orderDto;
        }).collect(Collectors.toList());

        BeanUtils.copyProperties(ordersPageInfo, ordersDtoPageInfo, "records");
        ordersDtoPageInfo.setRecords(orderDtoList);
    }

    /**
     * 再来一单
     *
     * @param map
     */
    @Transactional
    public void againSubmit(@RequestBody Map<String, String> map) {
        String ids = map.get("id");
        long id = Long.parseLong(ids);
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, id);
        //获取该订单对应的所有的订单明细表
        //SQL 语句：SELECT id,name,order_id,dish_id,setmeal_id,dish_flavor,number,amount,image FROM order_detail WHERE (order_id = ?);
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);

        //通过用户 id 把原来的购物车给清空
        shoppingCartService.clean();//此处的 clean 方法在视频中出现过,建议抽取到 service 层中以方便调用

        //获取用户 id
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item) -> {
            //把从 order 表中和 order_details 表中获取到的数据赋值给这个购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if (dishId != null) {
                //如果是菜品那就添加菜品的查询条件
                shoppingCart.setDishId(dishId);
            } else {
                //添加到购物车的是套餐
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        //把携带数据的购物车批量插入购物车表
        shoppingCartService.saveBatch(shoppingCartList);
    }

}
